package me.yuxiaoyao.jpa.nativesql.mapper;

import me.yuxiaoyao.jpa.nativesql.MapperNotFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * @author kerryzhang on 2020/12/16
 */


public class MapperConfiguration {

    private static final Map<String, JpaMapper> MAPPER_CACHE = new HashMap<>(4);
    private static SqlDateConverter sqlDateConverter = new DefaultSqlDateConverter();

    /**
     * default mapper
     */
    private static AutoMapper defaultMapper = new AutoMapper();

    public static Object mapper(Object sqlValue, Class<?> entityClassType, Class<?> fieldClassType, Class<? extends JpaMapper> mapperClass) {
        JpaMapper mapper;
        if (mapperClass == null) {
            mapper = defaultMapper;
        } else {
            mapper = MAPPER_CACHE.get(getClassKey(mapperClass));
            if (mapper == null) {
                throw new MapperNotFoundException(mapperClass + " not found check is register");
            }
        }
        return mapper.mapper(sqlValue, entityClassType, fieldClassType);
    }

    /**
     * 手动注册
     *
     * @param mappers
     */
    public static void registerMapper(JpaMapper... mappers) {
        for (JpaMapper mapper : mappers) {
            MAPPER_CACHE.put(getClassKey(mapper.getClass()), mapper);
        }
    }

    public static void setSqlDateConverter(SqlDateConverter sqlDateConverter) {
        MapperConfiguration.sqlDateConverter = sqlDateConverter;
    }

    public static SqlDateConverter getSqlDateConverter() {
        return sqlDateConverter;
    }


    public static void setDefaultMapper(AutoMapper defaultMapper) {
        MapperConfiguration.defaultMapper = defaultMapper;
    }


    private static String getClassKey(Class<?> cls) {
        return cls.getCanonicalName();
    }

}
